import 'package:fluent_ui/fluent_ui.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:go_router/go_router.dart';
import 'package:provider/provider.dart';

import '../../components/buttons.dart';
import '../../utils/date_utils.dart';
import 'semester_view_model.dart';

class SemesterViewEdit extends StatefulWidget {
  final String? id;

  const SemesterViewEdit({super.key, this.id});

  @override
  State<StatefulWidget> createState() => _SemesterViewEditState();
}

class _SemesterViewEditState extends State<SemesterViewEdit> {
  final formKey = GlobalKey<FormState>();

  @override
  void initState() {
    super.initState();
    //加载数据
    final model = context.read<SemesterViewModel>();
    model.loadInit(afterHandler: () => loadData(model));
  }

  ///加载数据
  void loadData(final SemesterViewModel model) {
    final String id = widget.id ?? '';
    if (id.isEmpty) {
      model.cleanInputFields();
      return;
    }
    model.getInfoById(id);
  }

  String buildTitle() {
    final isAdd = (widget.id ?? '').isEmpty;
    return '${isAdd ? '新增' : '编辑'}学年学期';
  }

  void popHandler(final bool ret) => context.pop<bool>(ret);

  void onSaveHandler(final SemesterViewModel model) {
    if (formKey.currentState?.validate() ?? false) {
      final id = widget.id ?? '';
      if (id.isNotEmpty) {
        //修改处理
        model.onModifyHandler(id, () => popHandler(true));
        return;
      }
      //新增处理
      model.onAddHandler(() => popHandler(true));
    }
  }

  @override
  Widget build(final BuildContext context) => Consumer<SemesterViewModel>(
        builder: (_, model, __) => ScaffoldPage.withPadding(
          header: PageHeader(title: Text(buildTitle())),
          content: buildForm(model),
          bottomBar: Padding(
            padding: EdgeInsetsDirectional.only(bottom: 20.h),
            child: OverflowBar(
              spacing: 2.0.w,
              children: [
                //保存
                buttons.save(onPressed: () => onSaveHandler(model)),
                //取消
                buttons.cancel(onPressed: () => popHandler(false))
              ],
            ),
          ),
        ),
      );

  Widget buildForm(final SemesterViewModel model) {
    final isAdd = (widget.id ?? '').isEmpty;

    Widget createContainer(Widget child) => Container(
          padding: EdgeInsetsDirectional.symmetric(vertical: 10.h),
          constraints: BoxConstraints(maxWidth: 268.w),
          child: child,
        );

    Widget createWidget(String label, Widget child) => createContainer(
          InfoLabel(
            label: label,
            child: child,
          ),
        );

    Widget createText(SemesterInputField field) => createWidget(
          field.label,
          () {
            final isDate = field == SemesterInputField.start ||
                field == SemesterInputField.end;
            final label = '${field.label}${isDate ? '[yyyy-MM-dd]' : ''}';
            final ctr = model.getController(field);
            return TextFormBox(
              controller: ctr,
              placeholder: label,
              maxLines: field == SemesterInputField.remark ? 3 : null,
              validator: (val) => field.validHandler(val),
              suffix: () {
                if (isDate) {
                  return IconButton(
                    icon: const Icon(FluentIcons.date_time),
                    onPressed: () async {
                      var current = dateUtils.parse('yyyy-MM-dd', ctr?.text);
                      final ret = await showDialog<DateTime?>(
                        context: context,
                        builder: (context) => ContentDialog(
                          content: DatePicker(
                            selected: current ?? DateTime.now(),
                            onCancel: () {
                              current = null;
                              Navigator.pop<DateTime?>(context, null);
                            },
                            onChanged: (dt) {
                              current = dt;
                              Navigator.pop<DateTime?>(context, current);
                            },
                          ),
                        ),
                      );
                      debugPrint(
                          '${field.label}=>[ret:$ret][current: $current]');
                      if (current != null) {
                        setState(() {
                          ctr?.text = dateUtils.format('yyyy-MM-dd', current);
                        });
                      }
                    },
                  );
                }
                return null;
              }(),
            );
          }(),
        );

    Widget createSwitch(SemesterInputField field) {
      final controller = model.getController(field);
      final child = ToggleSwitch(
        checked: () {
          final String val = controller?.text ?? '0';
          return (int.tryParse(val) ?? 0) == 1;
        }(),
        onChanged: (val) => setState(() => controller?.text = '${val ? 1 : 0}'),
      );
      return createWidget(field.label, child);
    }

    Widget createSwitchBars() {
      //是否默认
      final defSwitchWidget = createSwitch(SemesterInputField.isDef);
      if (isAdd) {
        return defSwitchWidget;
      }
      return createContainer(Row(children: [
        //是否默认
        defSwitchWidget,
        //占位
        SizedBox(width: 20.w),
        //状态
        createSwitch(SemesterInputField.status)
      ]));
    }

    return Form(
      key: formKey,
      autovalidateMode: AutovalidateMode.onUserInteraction,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          //编码
          createText(SemesterInputField.code),
          //标题
          createText(SemesterInputField.title),
          //备注
          createText(SemesterInputField.remark),
          //开始日期
          createText(SemesterInputField.start),
          //结束日期
          createText(SemesterInputField.end),
          //
          createSwitchBars(),
        ],
      ),
    );
  }
}
